package cn.xuchunh.campusbbs.ui.fragments;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

import cn.xuchunh.campusbbs.AppContext;
import cn.xuchunh.campusbbs.base.BaseRecyclerViewAdapter;
import cn.xuchunh.campusbbs.ui.activities.ForumActivity;
import cn.xuchunh.campusbbs.adapter.ChildForumAdapter;
import cn.xuchunh.campusbbs.base.BaseRefreshListFragment;
import cn.xuchunh.campusbbs.bean.Forum;
import cn.xuchunh.campusbbs.net.HttpRequestManager;
import cn.xuchunh.campusbbs.utils.IntentParamsKey;
import cn.xuchunh.campusbbs.utils.JsonParser;
import cn.xuchunh.campusbbs.viewholder.SimpleViewHolder;
import cn.xuchunh.campusbbs.widget.DividerItemDecoration;

/**
 * Created by XuChunH on 2015/9/26.
 */
public class ChildForumFragment extends BaseRefreshListFragment<SimpleViewHolder, Forum> {

    private int forumId;

    public static ChildForumFragment getInstance(int forumId) {
        ChildForumFragment childForumFragment = new ChildForumFragment();
        Bundle args = new Bundle();
        args.putInt(IntentParamsKey.FORUM_ID, forumId);
        childForumFragment.setArguments(args);
        return childForumFragment;
    }

    @Override
    protected RecyclerView.LayoutManager createLayoutManager() {
        return new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
    }

    @Override
    protected BaseRecyclerViewAdapter<SimpleViewHolder, Forum> createAdapter() {
        return new ChildForumAdapter(getActivity());
    }

    @Override
    protected void afterInitView() {
        super.afterInitView();
        getRecyclerView().addItemDecoration(new DividerItemDecoration(getActivity(),DividerItemDecoration.VERTICAL_LIST));
    }

    @Override
    protected List<Forum> parse(JSONObject jsonObject) throws JSONException {
        return JsonParser.parseForumList(jsonObject);
    }

    @Override
    protected void loadDataFromServer() {
        HttpRequestManager.getInstance(AppContext.getInstance()).
                loadChildForumList(forumId, new ListXJsonListener(), new SimpleErrorListener(), getVolleyTag());
    }

    @Override
    protected void loadDataFromCache() {

    }

    @Override
    public String getVolleyTag() {
        return ChildForumFragment.class.getSimpleName();
    }

    @Override
    public String getCacheKey() {
        return null;
    }

    @Override
    public void handleArgs(Bundle args) {
        if (args != null) {
            forumId = args.getInt(IntentParamsKey.FORUM_ID, 0);
        }
    }

    @Override
    public void onItemClick(int position, View item) {
        super.onItemClick(position, item);
        ForumActivity.launch(getActivity(), getAdapter().getItem(position));
    }
}
